package com.kookapi.asserts.impl;


import com.kookapi.asserts.AssertionComponent;
import com.kookapi.asserts.result.AssertionResult;
import io.restassured.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author bairimengchang
 * @version 1.0
 * @project java-test
 * @description 库存减少断言组件
 * @date 2025/9/29
 */
@Component("productStockAssertionComponent")
@Slf4j
public class ProductStockAssertionComponent implements AssertionComponent {

    @Override
    public AssertionResult execute(Response response, Map<String, Object> context) {
        log.info("执行库存减少断言");
        // 从上下文中取出对应的数据
        String beforeStock = (String) context.get("before_stock");
        String afterStock = (String) context.get("after_stock");
        String buyNum = (String) context.get("buy_num");

        // 检查必要参数是否存在
        if (beforeStock == null || afterStock == null || buyNum == null) {
            return AssertionResult.failure(String.format("库存减少校验失败，缺少必要参数: beforeStock=%s, afterStock=%s, buyNum=%s", beforeStock, afterStock, buyNum));
        }

        // 计算是否正确
        try {
            if (Integer.parseInt(afterStock) == Integer.parseInt(beforeStock) - Integer.parseInt(buyNum)) {
                return AssertionResult.success(String.format("库存减少校验成功，具体参数beforeStock=%s, afterStock=%s, buyNum=%s", beforeStock, afterStock, buyNum));
            }
            return AssertionResult.failure(String.format("库存减少校验失败，计算结果不匹配: beforeStock=%s, afterStock=%s, buyNum=%s", beforeStock, afterStock, buyNum));
        } catch (NumberFormatException e) {
            return AssertionResult.failure(String.format("库存减少校验失败，参数格式错误: beforeStock=%s, afterStock=%s, buyNum=%s", beforeStock, afterStock, buyNum));
        }
    }

}
